package com.affinity;


import com.affinity.impl.AffinityMaskSpi;
import com.affinity.impl.BaseThreadAffinityService;
import com.affinity.impl.SimpleCPULayoutService;
import com.affinity.impl.spi.FakeAffinityMaskSpi;
import com.affinity.impl.spi.PosixAffinityMaskSpi;
import com.affinity.impl.spi.WindowsAffinityMaskSpi;
import com.sun.jna.Platform;

/**
 * fixme: Class ThreadAffinityUtils is for porn
 *
 * @author cheremin
 * @since 27.04.12,  18:05
 */
public class ThreadAffinityUtils {


	private ThreadAffinityUtils() {
		throw new AssertionError( "Not for instantiation" );
	}

	private static final ThreadAffinityService affinityService;
	private static final CPULayoutService layoutService;

	static {
		final AffinityMaskSpi spi = getAffinitySpi();

		layoutService = new SimpleCPULayoutService();

		affinityService = new BaseThreadAffinityService(
				layoutService,
				spi
		);
	}

	private static AffinityMaskSpi getAffinitySpi() {
		AffinityMaskSpi spi;
		if( Platform.isWindows() ) {
			spi = new WindowsAffinityMaskSpi();
		} else {
			spi = new PosixAffinityMaskSpi();
		}
		try {
			spi.pingSpi();
			return spi;
		} catch( Throwable t ) {
			//TODO log error
			return new FakeAffinityMaskSpi();
		}
	}

	public static ThreadAffinityService defaultAffinityService() {
		return affinityService;
	}

	public static CPULayoutService defaultLayoutService() {
		return layoutService;
	}
}
